package com.diorsunion.hedge.task;

import com.diorsunion.hedge.bo.datasync.StockDataSync;
import com.diorsunion.hedge.dal.entity.stock.Stock;
import com.diorsunion.hedge.dal.repository.stock.StockRepository;
import com.diorsunion.hedge.web.util.LogUtil;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * Created by harley-dog<custer7572@163.com> on 2015/12/12.
 */
@Component
public class StockPriceSyncTask {
    @Value("#{config['runtime.environment']}")
    private String runtime;

    @Resource
    @Qualifier("DayDataSync")
    StockDataSync dayDataSync;

    @Resource
    @Qualifier("WeekDataSync")
    StockDataSync weekDataSync;

    @Resource
    @Qualifier("MonthDataSync")
    StockDataSync monthDataSync;

    @Resource
    StockRepository stockRepository;

    //每天6点执行
    @Scheduled(cron = "0 0 6 * * ?")
    void day() {
        if("product".equals(runtime)){
            dayrun();
        }
    }

    public void dayrun(){
        run(dayDataSync);
    }

    //每周星期六的7点执行
    @Scheduled(cron = "0 0 7 * * SUN")
    void week() {
        if("product".equals(runtime)){
            weekrun();
        }
    }

    public void weekrun(){
        run(weekDataSync);
    }

    //每月1号的8点执行
    @Scheduled(cron = "0 0 8 1 * ?")
    void month() {
        if("product".equals(runtime)){
            monthrun();
        }
    }

    public void monthrun(){
        run(monthDataSync);
    }


    public void run(StockDataSync stockDataSync) {
        Date date = new Date();
        List<Stock> stockSet = stockRepository.findAll(null, null);
        stockSet.stream().forEach(stock -> {
            try {
                stockDataSync.sync(date, stock);
            } catch (Exception e) {
                LogUtil.error(stock.code + " sync error", e);
            }
        });
    }

    /**
     * 同步指定的股票数据
     * @param stockDataSync
     * @param code
     */
    public void run(StockDataSync stockDataSync, String code) {
        Date date = new Date();
        Stock stock = stockRepository.get(code);
        try {
            if(stock!=null){
                stockDataSync.sync(date, stock);
            }
        } catch (Exception e) {
            LogUtil.error(stock.code + " sync error", e);
        }
    }
}
